package com.siwei.mes.tgl;


import com.alibaba.fastjson.JSON;
import com.siwei.mes.common.annotation.AnonymousAccess;
import com.siwei.mes.common.base.BaseParams;
import com.siwei.mes.common.result.ApiResult;
import com.siwei.mes.common.result.Json;
import com.siwei.mes.common.validator.bus.SyncGroup;
import com.siwei.mes.entity.tgl.TglContract;
import com.siwei.mes.mapper.ContractMapper;
import com.siwei.mes.tgl.queue.TglProcessorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * @Description: tgl合同
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2023/12/6 21:09
 */
@RestController
@Api(tags = "对外给砼行的接口")
@RequestMapping("tgl/contract")
public class TglContractController {
    private static final Logger log = LoggerFactory.getLogger("tgl");

    @Value("${tgl-token}")
    private String TLG_TOKEN;

    @Resource
    private ContractMapper contractMapper;

    @Resource
    private TglProcessorService processor;

    /**
     * 校验token
     *
     * @param request
     */
    public void checkToken(HttpServletRequest request) {
        String token = request.getHeader(BaseParams.Authorization);
        assertTrue(StringUtils.isBlank(token), "授权token为空");
        assertTrue(!token.equals(TLG_TOKEN), "token不正确");
    }

    @AnonymousAccess
    @ApiOperation(value = "新增或删除合同")
    @PostMapping("/saveOrUpdate")
    public Json saveOrUpdate(@RequestBody @Validated(SyncGroup.class) TglContract entity, HttpServletRequest request) {
        log.info("TGL新增或修改合同,入参：{}", JSON.toJSONString(entity));
        this.checkToken(request);
        processor.submitRequest(entity);
        return Json.succ().data(entity);
    }

    @AnonymousAccess
    @ApiOperation(value = "删除合同")
    @PostMapping("/delete")
    public Json delete(@RequestBody TglContract entity, HttpServletRequest request) {
        this.checkToken(request);
        log.info("TGL删除合同,入参：{}", entity.getCid());
        assertTrue(entity.getCid() == null, "TGL合同id为空");
        TglContract localInfo = contractMapper.selectByCid(entity.getCid());
        if (localInfo != null) {
            contractMapper.deleteByPrimaryKey(localInfo.getId());
        }
        return Json.succ().data(new ApiResult());
    }
}
